<template>
	<view class="container">
		<!-- 门店选择器 -->
		<view class="store-select-bar">
			<picker :range="storeNames" @change="onStoreChange">
				<view class="store-picker">
					当前门店：{{ currentStoreName }}
				</view>
			</picker>
		</view>
		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="search-input" @click="goToSearch">
				<text class="search-icon">🔍</text>
				<text class="search-placeholder">搜索零食</text>
			</view>
		</view>

		<!-- 轮播图 -->
		<banner-swiper />

		<!-- 分类导航 -->
		<view class="category-section">
			<view class="section-title">商品分类</view>
			<view class="category-grid">
				<view class="category-item" v-for="category in topCategories" :key="category.id"
					@click="goToCategory(category)">
					<image :src="category.iconUrl || '/static/images/default-category.png'" class="category-icon" />
					<text class="category-name">{{ category.name }}</text>
				</view>
			</view>
		</view>

		<!-- 热门商品 -->
		<view class="hot-section">
			<view class="section-header">
				<text class="section-title">热门商品</text>
				<text class="more-link" @click="goToProductList">查看更多</text>
			</view>
			<view class="product-grid">
				<product-card v-for="product in hotProductsWithCart" :key="product.id" :product="product"
					:cartCount="product.cartCount" @cart-updated="onCartUpdated" />
			</view>
		</view>

		<!-- 新品推荐 -->
		<view class="new-section">
			<view class="section-header">
				<text class="section-title">新品推荐</text>
				<text class="more-link" @click="goToProductList">查看更多</text>
			</view>
			<view class="product-grid">
				<product-card v-for="product in newProductsWithCart" :key="product.id" :product="product"
					:cartCount="product.cartCount" @cart-updated="onCartUpdated" />
			</view>
		</view>

		<!-- 加载更多 -->
		<view v-if="loading" class="loading">
			<text>加载中...</text>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		computed
	} from 'vue';
	import {
		onShow,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	import {
		categoryApi,
		productApi,
		storesApi,
		cartApi
	} from '@/api/index.js';
	import common from '@/utils/common.js';
	import ProductCard from '@/components/product-card.vue';
	import BannerSwiper from '@/components/BannerSwiper.vue';
	import { getCartCount, setCartCount, removeCartCount } from '@/utils/cartStore.js';
	import storage from '@/utils/storage.js';

	// 门店相关数据
	const stores = ref([]);
	const storeNames = ref([]);
	const currentStoreId = ref(null);
	const currentStoreName = ref('');

	// 首页其他数据
	const topCategories = ref([]);
	const hotProducts = ref([]);
	const newProducts = ref([]);
	const loading = ref(false);
	const cartMap = ref({}); // 商品id+skuId => 数量

	// 获取商品的skuId
	const getSkuId = (product) => {
		if (product.skuId) return product.skuId;
		if (product.skus && product.skus.length > 0) return product.skus[0].id;
		if (product.sku && product.sku.id) return product.sku.id;
		return 0;
	};

	// 计算热门商品带cartCount
	const hotProductsWithCart = computed(() => {
		return hotProducts.value.map(product => {
			const skuId = getSkuId(product);
			return {
				...product,
				cartCount: cartMap.value[`${product.id}_${skuId}`] || 0
			};
		});
	});

	// 计算新品推荐带cartCount
	const newProductsWithCart = computed(() => {
		return newProducts.value.map(product => {
			const skuId = getSkuId(product);
			return {
				...product,
				cartCount: cartMap.value[`${product.id}_${skuId}`] || 0
			};
		});
	});

	// 获取门店列表
	const loadStores = async () => {
		const res = await storesApi.getStores();
		if (res.code === 200) {
			stores.value = res.data.items || [];
			storeNames.value = stores.value.map(s => s.name);
			
			// 优先使用本地存储的门店ID
			const savedStoreId = storage.getCurrentStoreId();
			const savedStoreName = storage.getCurrentStoreName();
			
			if (savedStoreId && stores.value.some(s => s.id === savedStoreId)) {
				// 如果本地存储的门店ID在当前门店列表中，则使用它
				currentStoreId.value = savedStoreId;
				currentStoreName.value = savedStoreName;
			} else if (stores.value.length > 0) {
				// 否则默认选第一个门店
				currentStoreId.value = stores.value[0].id;
				currentStoreName.value = stores.value[0].name;
				
				// 存储当前选择的门店信息
				storage.setCurrentStoreId(currentStoreId.value);
				storage.setCurrentStoreName(currentStoreName.value);
			}
		}
	};

	// 门店切换
	const onStoreChange = (e) => {
		const idx = e.detail.value;
		currentStoreId.value = stores.value[idx].id;
		currentStoreName.value = stores.value[idx].name;
		
		// 存储当前选择的门店信息
		storage.setCurrentStoreId(currentStoreId.value);
		storage.setCurrentStoreName(currentStoreName.value);
		
		loadData();
	};

	// 加载购物车数据
	const loadCart = async () => {
		const res = await cartApi.getCart();
		const map = {};
		if (res.code === 200 && res.data && res.data.items) {
			res.data.items.forEach(item => {
				// 用 productId_skuId 作为key
				map[`${item.product.id}_${item.sku.id}`] = item.quantity;
			});
		}
		cartMap.value = map;
	};

	// 修改loadData方法中加载商品数据的部分
	const loadData = async () => {
		try {
			common.showLoading('加载中...');
			loading.value = true;
			if (!currentStoreId.value) {
				await loadStores();
			}
			const [categoriesRes, hotRes, newRes] = await Promise.all([
				categoryApi.getTopCategories({
					storeId: currentStoreId.value
				}),
				productApi.getPopularProducts(6, currentStoreId.value),
				productApi.getNewProducts(6, currentStoreId.value)
			]);
			topCategories.value = categoriesRes.data || [];
			hotProducts.value = hotRes.data || [];
			newProducts.value = newRes.data || [];
			await loadCart();
		} catch (error) {
			console.error('加载首页数据失败:', error);
			common.showError('加载失败');
		} finally {
			loading.value = false;
			common.hideLoading();
		}
	};

	// 页面跳转方法
	const goToSearch = () => {
		uni.navigateTo({
			url: '/pages/search/search'
		});
	};

	const goToCategory = (category) => {
		uni.navigateTo({
			url: `/pages/product/list?categoryId=${category.id}&categoryName=${category.name}&storeId=${currentStoreId.value}`
		});
	};

	const goToProductList = () => {
		uni.switchTab({
			url: '/pages/category/category'
		});
	};

	// 监听购物车变化，刷新购物车数据
	const onCartUpdated = () => {
		loadCart();
		loadCartCount();
	};

	// 设置tabbar购物车角标
	const setCartTabBadge = (count) => {
		if (count > 0) {
			uni.setTabBarBadge({
				index: 2,
				text: String(count)
			});
		} else {
			uni.removeTabBarBadge({ index: 2 });
		}
	};

	// 首页加载购物车数量
	const loadCartCount = async () => {
		try {
			const res = await cartApi.getCartCount();
			if (res.code === 200 && typeof res.data === 'number') {
				setCartCount(res.data);
				setCartTabBadge(res.data);
			} else {
				setCartCount(0);
				setCartTabBadge(0);
			}
		} catch (e) {
			setCartCount(0);
			setCartTabBadge(0);
		}
	};

	onShow(() => {
		loadStores().then(() => {
			loadData();
		});
		loadCartCount();
	});

	// 离开首页时清除角标和store
	// onHide(() => {
	// 	removeCartCount();
	// 	uni.removeTabBarBadge({ index: 2 });
	// });

	// 下拉刷新处理 - 使用uni-app生命周期函数
	onPullDownRefresh(() => {
		console.log("下拉刷新触发");
		loadData().then(() => {
			console.log("刷新完成，停止下拉刷新动画");
			uni.stopPullDownRefresh();
		});
	});
</script>

<style scoped>
	.container {
		padding: 20rpx;
		background: #f5f5f5;
		min-height: 100vh;
	}

	.store-select-bar {
		margin-bottom: 20rpx;
	}

	.store-picker {
		background: #fff;
		border-radius: 25rpx;
		padding: 16rpx 30rpx;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
	}

	.search-bar {
		margin-bottom: 20rpx;
	}

	.search-input {
		background: #fff;
		border-radius: 25rpx;
		padding: 20rpx 30rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.search-icon {
		margin-right: 10rpx;
		font-size: 28rpx;
	}

	.search-placeholder {
		color: #999;
		font-size: 28rpx;
	}

	.category-section {
		background: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
	}

	.category-grid {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 20rpx;
	}

	.category-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20rpx 10rpx;
	}

	.category-icon {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		margin-bottom: 10rpx;
	}

	.category-name {
		font-size: 24rpx;
		color: #333;
		text-align: center;
	}

	.hot-section,
	.new-section {
		background: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.more-link {
		font-size: 26rpx;
		color: #666;
	}

	.product-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 20rpx;
	}

	.loading {
		text-align: center;
		padding: 30rpx;
		color: #999;
	}
</style>